package us.styx.net;

import java.nio.channels.SelectionKey;
import java.util.Iterator;

public class NetworkSelector implements Runnable {
    
    @Override
    public void run() {
	NetworkEvent networkEvent = new NetworkEventHandler();
	while (NetworkServer.getServerSocketChannel().isOpen() && NetworkServer.getServerSocketChannel() != null) {
	    try {
		NetworkServer.selector.select();
		Iterator<SelectionKey> selectionKeys = NetworkServer.selector.selectedKeys().iterator();
		while (selectionKeys.hasNext()) {
		    SelectionKey key = (SelectionKey) selectionKeys.next();
		    selectionKeys.remove();
		    if (!key.isValid()) {
			continue;
		    }
		    if (key.isAcceptable()) {
			networkEvent.acceptConnection(key);
		    }
		    if (key.isReadable()) {
			networkEvent.readData(key);
		    }
		}
	    } catch (Exception exception) {
		exception.printStackTrace();
	    }
	}
    }
}